package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.DeleteDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.MultiUnitItemPoJo;
import com.xbongbong.paas.field.SaasParticularAttributePoJo;
import com.xbongbong.paas.field.UnitItemPoJo;
import com.xbongbong.paas.pojo.ProductFieldPojo;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.CostAdjustDao;
import com.xbongbong.saas.domain.entity.CostAdjustProductEntity;
import com.xbongbong.saas.domain.entity.ProductBaseInfoEntity;
import com.xbongbong.saas.domain.entity.ext.CostAdjustEntityExt;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.enums.RelativeProductEnum;
import com.xbongbong.saas.enums.UpdateDataTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CostAdjustEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.product.CostAdjustProductEnum;
import com.xbongbong.saas.help.ExplainHelp;
import com.xbongbong.saas.help.SaasFormHelp;
import com.xbongbong.saas.help.ShowFormatHelp;
import com.xbongbong.saas.model.CostAdjustModel;
import com.xbongbong.saas.model.CostAdjustProductModel;
import com.xbongbong.saas.model.CostAdjustSubDataModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;

/**
 * @author WuHB
 * @date 2021/11/19 17:01
 */
@Service("costAdjustModel")
public class CostAdjustModelImpl implements CostAdjustModel {

    @Resource
    private CostAdjustDao costAdjustDao;

    @Resource
    private PaasEsModel paasEsModel;

    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;

    @Resource
    private ProductModel productModel;

    @Resource
    private CostAdjustProductModel costAdjustProductModel;

    @Resource
    private ExplainHelp explainHelp;

    @Resource
    private CostAdjustSubDataModel costAdjustSubDataModel;

    @Resource
    private SaasFormHelp saasFormHelp;

    @Resource
    private ShowFormatHelp showFormatHelp;

    /**
     * 插入
     *
     * @param entity 实体
     * @return 是否成功
     * @throws XbbException 数据库操作异常
     */
    @Override
    public Integer insert(CostAdjustEntityExt entity) throws XbbException {
        // 先进行数据库的插入动作
        long now = DateTimeUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_COST_ADJUST_SUB);
        Integer insertId = costAdjustDao.insert(entity);
        // 插入ES
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        BeanUtil.copyProperties(entity, paasFormDataEntity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_COST_ADJUST);
        paasEsModel.insert(insertDTO);

        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_COST_ADJUST_SUB);
        return insertId;
    }

    /**
     * 更新
     *
     * @param entity 实体
     * @return 是否成功
     * @throws XbbException 数据库操作异常
     */
    @Override
    public Integer update(CostAdjustEntityExt entity) throws XbbException {
        entity.setUpdateTime(DateTimeUtil.getInt());

        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_COST_ADJUST_SUB);
        Integer success = costAdjustDao.update(entity);
        Integer updateSub = paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_COST_ADJUST_SUB);

        if (Objects.equals(1, success) || Objects.equals(1, updateSub)) {
            success = costAdjustDao.updateTime(DateTimeUtil.getInt(), entity.getId(), entity.getCorpid());
            // 更新ES
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entity, paasFormDataEntity, false);
            InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_COST_ADJUST);
            insertDTO.getSource().remove("creatorId");
            paasEsModel.update(insertDTO);
        }
        if (Objects.nonNull(entity.getSubFormData()) && !entity.getSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSubFormData());
        }
        return success;
    }

    /**
     * 获取符合查询条件的记录
     *
     * @param param 查询条件
     * @return 符合查询条件的记录
     */
    @Override
    public List<CostAdjustEntityExt> findEntitys(Map<String, Object> param) {
        List<CostAdjustEntityExt> entitys = costAdjustDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_COST_ADJUST_SUB);
        }
        return entitys;
    }

    /**
     * 获取符合查询条件的记录总数
     *
     * @param param 查询条件
     * @return 符合查询条件的记录总数
     */
    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return costAdjustDao.getEntitysCount(param);
    }

    /**
     * Description: 查询符合条件的数据（无子表单数据）
     *
     * @param param
     * @return java.util.List<T>
     */
    @Override
    public List<CostAdjustEntityExt> findEntitysWithoutSub(Map<String, Object> param) {
        return null;
    }

    @Override
    public CostAdjustEntityExt getByKey(Long dataId, String corpid) {
        CostAdjustEntityExt entity = costAdjustDao.getByKey(dataId, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(entity), IndexTypeEnum.IDX_SAAS_COST_ADJUST_SUB);
        return entity;
    }

    @Override
    public void formatProduct4Show2(Long dataId, String corpid, JSONObject data, UpdateDataTypeEnum updateDataTypeEnum) throws XbbException {
        List<CostAdjustProductEntity> costAdjustProductEntityList = new ArrayList<>();
        List<ProductBaseInfoEntity> productBaseInfoEntityList = new ArrayList<>();
        Set<Long> productIdList = new HashSet<>();
        boolean approve = false;
        // 审批数据获取
        if (Objects.isNull(dataId) || Objects.equals(dataId, 0L)) {
            approve = true;
            if (data.get(CostAdjustEnum.PRODUCT.getAttr()) instanceof JSONObject) {
                JSONArray productArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(FastJsonHelper.getJsonObjectOrDefaultFromFormData(data, CostAdjustEnum.PRODUCT.getAttr(), new JSONObject()), StringConstant.PRODUCT_LIST, new JSONArray());
                Map<Long, ProductEntityExt> productMap = productModel.getProductMap(productIdList, corpid, productArray);
                formatProductList(corpid, costAdjustProductEntityList, productBaseInfoEntityList, data, productMap);
            } else {
                JSONArray jsonArray = data.getJSONArray(CostAdjustEnum.PRODUCT.getAttr());
                if (Objects.nonNull(jsonArray)) {
                    List<Long> productIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);
                        // 页面传入的产品的id
                        Long productId = object.getLong(CostAdjustProductEnum.PRODUCT.getAttr());
                        if (Objects.nonNull(productId)) {
                            productIdIn.add(productId);
                            productIdList.add(productId);
                        }
                    }
                    // 获取产品信息
                    Map<Long, ProductEntityExt> productMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    if (productIdIn.size() >= 1) {
                        // 从产品表中获取对应的产品信息
                        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        params.put("corpid", corpid);
                        params.put("idIn", productIdIn);
                        params.put("del", 0);
                        List<ProductEntityExt> productModelEntitys = productModel.findEntitys(params);
                        if (productModelEntitys != null) {
                            for (ProductEntityExt entity : productModelEntitys) {
                                productMap.put(entity.getId(), entity);
                            }
                        }
                    }
                    formatNewProductList(corpid, costAdjustProductEntityList, productBaseInfoEntityList, jsonArray, productMap);
                }
            }
        } else {
            // 检索del=0和del=6的数据，del=6是工作流中审批节点拒绝和撤回产生的数据，不是通过审批拒绝、撤回的数据不会产生del=6的数据，如果拒绝和撤回重新提交后，del=6将会被置回del=0
            costAdjustProductEntityList = costAdjustProductModel.listByAdjustId(corpid, dataId, Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.APPROVE_FAILED.getDel()));
            List<Long> refIdList = new ArrayList<>();
            costAdjustProductEntityList.forEach(item -> {
                productIdList.add(item.getProductId());
                refIdList.add(item.getId());
            });
            if (refIdList.isEmpty()) {
                return;
            }
        }
        List<Long> warehouseIdList = costAdjustProductEntityList.stream().map(CostAdjustProductEntity::getWarehouseId).collect(Collectors.toList());
        List<PaasFormDataEntityExt> warehouseList = paasEsModel.getByIdList(warehouseIdList, corpid, SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.WAREHOUSE.getCode(), new ArrayList<>(), IndexTypeEnum.IDX_SAAS_WAREHOUSE);
        JSONArray productArray = new JSONArray();
        for (CostAdjustProductEntity productEntity : costAdjustProductEntityList) {
            JSONObject jsonObject = costAdjustProductModel.formatSingleProduct(productEntity, warehouseList);
            if (approve) {
                jsonObject.put(CostAdjustProductEnum.GUARANTEE_PERIOD.getAttr(), productEntity.getGuaranteePeriod());
            }
            productArray.add(jsonObject);
        }
        data.put(CostAdjustEnum.PRODUCT.getAttr(), productArray);
    }

    @Override
    public void formatUpdateExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
        String corpid = formatExplainDTO.getCorpid();
        String platForm = formatExplainDTO.getPlatform();
        // 调整单默认字段
        List<String> nonEditableList = CostAdjustEnum.getNonEditableList();
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            Integer fieldType = fieldAttrEntity.getFieldType();
            if (Objects.equals(fieldType, FieldTypeEnum.SELECT_PRODUCT.getType())) {
                fieldAttrEntity.setSupportScanning(BasicConstant.ONE);
                explainHelp.formatSelectProductExplains(fieldAttrEntity, XbbRefTypeEnum.COST_ADJUST, corpid, BasicConstant.ONE, false);
                if (Objects.isNull(formatExplainDTO.getFromCopy()) || !formatExplainDTO.getFromCopy()) {
                    List<? extends FieldAttrEntity> subExplainList = fieldAttrEntity.getSubForm().getItems();
                    subExplainList.forEach(item -> item.setEditable(0));
                    fieldAttrEntity.getSubForm().setItems(subExplainList);
                }
                if (Objects.equals(platForm, PlatFormEnum.DINGTALK.getValue())) {
                    SaasParticularAttributePoJo saasParticularAttributePoJo = fieldAttrEntity.getSaasParticularAttributePoJo();
                    saasParticularAttributePoJo.setProductRelyAttr(CostAdjustProductEnum.WAREHOUSE.getAttr());
                }
            }
            if (Objects.equals(fieldAttrEntity.getAttr(), CostAdjustEnum.WAREHOUSE_ID.getAttr())) {
                fieldAttrEntity.setEditable(0);
            }
            if (nonEditableList.contains(fieldAttrEntity.getAttr())) {
                fieldAttrEntity.setEditable(0);
            }
        }
    }

    @Override
    public Integer deleteById(Long id, String corpid) throws XbbException {
        DeleteDTO deleteDTO = new DeleteDTO();
        deleteDTO.setEsId(corpid + "_" + id);
        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_COST_ADJUST);
        paasEsModel.delete(deleteDTO);
        return costAdjustDao.deleteById(id, corpid);
    }

    /**
     * 批量更新
     *
     * @param updateDataList 修改信息列表
     * @param corpid         公司ID
     * @return 影响行数
     * @throws XbbException 异常
     */
    @Override
    public Integer updateBatch(List<UpdateDataEntity> updateDataList, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateDataList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateDataList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateDataList)) {
            integer = costAdjustDao.updateBatch(updateDataList, corpid);
            paasEsModel.updateBatchMuchField(updateDataList, IndexTypeEnum.IDX_SAAS_COST_ADJUST);
        }
        if (CollectionsUtil.isNotEmpty(subList)) {
            costAdjustSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    /**
     * 批量更新
     *
     * @param updateDataList 修改信息列表
     * @param corpid         公司ID
     * @param refreshPolicy  refreshPolicy
     * @return 影响行数
     * @throws XbbException 异常
     */
    @Override
    public Integer updateBatch(List<UpdateDataEntity> updateDataList, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateDataList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateDataList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateDataList)) {
            integer = costAdjustDao.updateBatch(updateDataList, corpid);
            paasEsModel.updateBatchMuchField(updateDataList, IndexTypeEnum.IDX_SAAS_COST_ADJUST, refreshPolicy);
        }
        if (!subList.isEmpty()) {
            costAdjustSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    /**
     * 批量更新团队
     *
     * @param dataIdList    数据ID
     * @param corpid        公司ID
     * @param userId        用户ID
     * @param refreshPolicy WriteRequest.RefreshPolicy
     * @return 影响行数
     * @throws XbbException 异常
     */
    @Override
    public Integer batchUpdateOwner(List<Long> dataIdList, String corpid, String userId, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        Integer integer = costAdjustDao.batchUpdateOwner(dataIdList, corpid, userId);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (Long id : dataIdList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(corpid + "_" + id);
            Map<String, Object> map = new HashMap<>();
            map.put(FieldTypeEnum.OWNERID.getAlias(), userId);
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_COST_ADJUST);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertDTOList, refreshPolicy);
        return integer;
    }

    private void formatProductList(String corpid, List<CostAdjustProductEntity> inventoryProducts, List<ProductBaseInfoEntity> productBaseInfoList, JSONObject data, Map<Long, ProductEntityExt> productMap) throws XbbException {
        Integer sort = 0;
        JSONArray productArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(FastJsonHelper.getJsonObjectOrDefaultFromFormData(data, CostAdjustEnum.PRODUCT.getAttr(), new JSONObject()), StringConstant.PRODUCT_LIST, new JSONArray());
        for (int i = 0; i < productArray.size(); i++) {
            JSONObject productArrayJSONObject = productArray.getJSONObject(i);
            sort++;
            // 页面传入的产品id
            Long pageProductId = FastJsonHelper.getLongOrDefaultFromFormData(productArrayJSONObject, StringConstant.SAAS_LINK_BUSINESS_ID, 0L);
            // 仓库
            JSONObject warehouse = FastJsonHelper.getJsonObjectFromFormData(productArrayJSONObject, RelativeProductEnum.WAREHOUSE.getSaasAttr());
            Long warehouseId = 0L;
            if (warehouse != null && warehouse.size() > 0) {
                warehouseId = warehouse.getLong(StringConstant.SAAS_LINK_BUSINESS_ID);
            }
            // 批次
            String batch = FastJsonHelper.getStringOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.BATCH.getSaasAttr(), "");
            // 生产日期
            Long date = DateTimeUtil.getInt(FastJsonHelper.getStringOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.PRODUCE_DATE.getSaasAttr(), ""), DateUtil.SDFDate);
            // 保质期 存的是天数
            Long guaranteePeriod = FastJsonHelper.getLongFromFormData(productArrayJSONObject, RelativeProductEnum.GUARANTEE_PERIOD.getSaasAttr());
            // 产品备注
            String memo = FastJsonHelper.getStringOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.MEMO.getSaasAttr(), "");
            if (productMap.containsKey(pageProductId)) {
                ProductEntityExt product = productMap.get(pageProductId);
                JSONObject productObject = product.getData();
                String specification = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), "");
                String productName = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.NAME.getAttr(), "");
                Double price = getDoubleOrDefaultFromFormData(productObject, ProductEnum.PRICE.getAttr(), 0D);
                String productNo = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.PRODUCT_NO.getAttr(), "");
                String unit = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.UNIT.getAttr(), "");
                String barcode = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.BARCODE.getAttr(), "");
                Long parentId = FastJsonHelper.getLongOrDefaultFromFormData(productObject, ProductEnum.PARENT_ID.getAttr(), 0L);
                CostAdjustProductEntity productEntity = new CostAdjustProductEntity();
                productEntity.setCorpid(corpid);
                productEntity.setProductId(pageProductId);
                productEntity.setParentId(parentId);
                productEntity.setProductName(productName);
                productEntity.setProductNo(productNo);
                productEntity.setWarehouseId(warehouseId);
                productEntity.setProductSpecification(specification);
                productEntity.setProductUnit(unit);
                productEntity.setSort(sort);
                // 增加关联id 为了和baseInfo有关联
                Long id = new Random().nextLong();
                productEntity.setId(id);
                inventoryProducts.add(productEntity);
                // baseInfo冗余信息
                ProductBaseInfoEntity productBaseInfoEntity = new ProductBaseInfoEntity();
                productBaseInfoEntity.setBatch(batch);
                if (guaranteePeriod != null) {
                    productBaseInfoEntity.setGuaranteePeriod(guaranteePeriod * 86400);
                }
                productBaseInfoEntity.setProduceDate(date);
                productBaseInfoEntity.setRefId(id);
                productBaseInfoEntity.setRefType(XbbRefTypeEnum.COST_ADJUST_PRODUCT.getCode());
                productBaseInfoEntity.setMemo(memo);
                productBaseInfoList.add(productBaseInfoEntity);
            }
        }
    }


    private void formatNewProductList(String corpid, List<CostAdjustProductEntity> costAdjustProductEntityList, List<ProductBaseInfoEntity> productBaseInfoList, JSONArray productArray, Map<Long, ProductEntityExt> productMap) throws XbbException {
        Integer sort = 0;
        for (int i = 0; i < productArray.size(); i++) {
            sort++;
            JSONObject pageProductObject = productArray.getJSONObject(i);
            Long pageProductId = pageProductObject.getLong(CostAdjustProductEnum.PRODUCT.getAttr());
            Double oriNum = getDoubleOrDefaultFromFormData(pageProductObject, CostAdjustProductEnum.STOCK.getAttr(), 0D);
            String batch = FastJsonHelper.getStringOrDefaultFromFormData(pageProductObject, CostAdjustProductEnum.BATCH.getAttr(), "");
            Long subProductId = FastJsonHelper.getLongFromFormData(pageProductObject, BusinessConstant.PRODUCT_SUB_ID);
            Long warehouseId = this.getWarehouseId(pageProductObject.getJSONArray(CostAdjustProductEnum.WAREHOUSE.getAttr()));
            BigDecimal costAdjustAmount = pageProductObject.getBigDecimal(CostAdjustProductEnum.ADJUST_AMOUNT.getAttr());
            BigDecimal oldCost = pageProductObject.getBigDecimal(CostAdjustProductEnum.OLD_COST.getAttr());
            BigDecimal newCost = pageProductObject.getBigDecimal(CostAdjustProductEnum.NEW_COST.getAttr());
            BigDecimal totalCost = pageProductObject.getBigDecimal(CostAdjustProductEnum.TOTAL_COST.getAttr());
            Long produceDate = FastJsonHelper.getLongOrDefaultFromFormData(pageProductObject, CostAdjustProductEnum.PRODUCE_DATE.getAttr(), 0L);
            Long guaranteePeriod = FastJsonHelper.getLongOrDefaultFromFormData(pageProductObject, CostAdjustProductEnum.GUARANTEE_PERIOD.getAttr(), 0L);
            if (productMap.containsKey(pageProductId)) {
                ProductEntityExt product = productMap.get(pageProductId);
                JSONObject productObject = product.getData();
                ProductFieldPojo productFieldPojo = saasFormHelp.getProductFieldPojo(RedisPrefixConstant.PRODUCT_UNIT, ProductEnum.UNIT.getAttr(), corpid);
                String specification = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), "");
                String productName = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.NAME.getAttr(), "");
                String productNo = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.PRODUCT_NO.getAttr(), "");
                String unit = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.UNIT.getAttr(), "");
                Long parentId = FastJsonHelper.getLongOrDefaultFromFormData(productObject, ProductEnum.PARENT_ID.getAttr(), 0L);
                CostAdjustProductEntity productEntity = new CostAdjustProductEntity();
                productEntity.setCorpid(corpid);
                productEntity.setProductId(pageProductId);
                productEntity.setParentId(parentId);
                productEntity.setProductName(productName);
                productEntity.setProductNo(productNo);
                productEntity.setProductSpecification(specification);
                productEntity.setProductUnit(unit);
                productEntity.setWarehouseId(warehouseId);
                productEntity.setProduceDate(produceDate);
                productEntity.setGuaranteePeriod(guaranteePeriod);
                productEntity.setBatch(batch);
                productEntity.setCostAdjustAmount(costAdjustAmount);
                productEntity.setOldCost(oldCost);
                productEntity.setNewCost(newCost);
                productEntity.setTotalCost(totalCost);
                productEntity.setSort(sort);
                productEntity.setInventoryNumber(BigDecimal.valueOf(oriNum));
                Long id = (long) -sort;
                if (Objects.nonNull(subProductId)) {
                    id = subProductId;
                }
                String unitId = pageProductObject.getString(CostAdjustProductEnum.BASIC_UNIT.getAttr());
                productEntity.setProductUnit(unitId);
                Integer enableMultiUnit = pageProductObject.getInteger(ProductEnum.ENABLE_MULTI_UNIT.getAttr());
                if (Objects.nonNull(enableMultiUnit) && Objects.equals(enableMultiUnit, 1)) {
                    List<MultiUnitItemPoJo> multiItems = productFieldPojo.getMultiItems();
                    MultiUnitItemPoJo multiUnitItemPoJo = null;
                    if (CollectionUtils.isNotEmpty(multiItems)) {
                        multiUnitItemPoJo = multiItems.stream().filter(item -> Objects.equals(unitId, String.valueOf(item.getValue()))).findFirst().orElse(null);
                    }
                    if (Objects.nonNull(multiUnitItemPoJo)) {
                        productEntity.setBusinessUnit(multiUnitItemPoJo.getBaseValue());
                        List<UnitItemPoJo> itemDataPoJoList = multiUnitItemPoJo.getItemDataPoJoList();
                        MultiUnitItemPoJo finalMultiUnitItemPoJo = multiUnitItemPoJo;
                        UnitItemPoJo unitItemPoJo = itemDataPoJoList.stream().filter(item -> Objects.equals(finalMultiUnitItemPoJo.getBaseValue(), item.getValue())).findFirst().orElse(new UnitItemPoJo());
                        productEntity.setRate(unitItemPoJo.getRate());
                        productEntity.setGroupId(multiUnitItemPoJo.getValue());
                        productEntity.setProductUnit(String.valueOf(multiUnitItemPoJo.getBaseValue()));
                    }
                } else {
                    pageProductObject.put(CostAdjustProductEnum.BASIC_UNIT.getAttr(), pageProductObject.getString(ProductEnum.UNIT.getAttr()));
                }
                productEntity.setId(id);
                costAdjustProductEntityList.add(productEntity);
                // baseInfo冗余信息

                ProductBaseInfoEntity productBaseInfoEntity = new ProductBaseInfoEntity();
                productBaseInfoEntity.setBatch(batch);
                productBaseInfoEntity.setRefId(id);
                productBaseInfoEntity.setRefType(XbbRefTypeEnum.COST_ADJUST_PRODUCT.getCode());
                productBaseInfoList.add(productBaseInfoEntity);
            }
        }
    }

    /**
     * 获取仓库ID
     *
     * @param jsonArray 仓库信息
     * @return 仓库ID
     * @throws XbbException 异常
     */
    private Long getWarehouseId(JSONArray jsonArray) throws XbbException {
        if (CollectionsUtil.isEmpty(jsonArray)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100002, MessageConstant.WAREHOUSE_INFO_NOT_EMPTY);
        }
        Long warehouseId = null;
        for (int j = 0; j < jsonArray.size(); j++) {
            JSONObject warehouseInfo = jsonArray.getJSONObject(j);
            if (MapUtils.isEmpty(warehouseInfo)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100002, MessageConstant.WAREHOUSE_INFO_NOT_EMPTY);
            }
            warehouseId = warehouseInfo.getLong("id");
            if (Objects.isNull(warehouseId)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100002, MessageConstant.WAREHOUSE_INFO_NOT_EMPTY);
            }
        }
        return warehouseId;
    }

    @Override
    public CostAdjustEntityExt getEntityById(Long dataId , String corpid) throws XbbException{
        CostAdjustEntityExt entity = costAdjustDao.getEntityById(dataId , corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(entity), IndexTypeEnum.IDX_SAAS_COST_ADJUST_SUB);
        return entity;
    }

    /**
     * 更新流程状态
     *
     * @param entity 实体
     * @return 是否成功
     * @throws XbbException 数据库操作异常
     */
    @Override
    public Integer updateFlowStatus(CostAdjustEntityExt entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setUpdateTime(now);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_COST_ADJUST_SUB);
        Integer success = costAdjustDao.updateFlowStatus(entity);
        Integer updateSub = paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_COST_ADJUST_SUB);
        if (Objects.equals(1, success) || Objects.equals(1, updateSub)) {
            // 更新时间
            success = costAdjustDao.updateTime(DateTimeUtil.getInt(), entity.getId(), entity.getCorpid());
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entity, paasFormDataEntity, false);
            InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_COST_ADJUST);
            paasEsModel.update(insertDTO);
        }
        if (Objects.nonNull(entity.getSubFormData()) && !entity.getSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSubFormData());
        }
        if (Objects.nonNull(entity.getSingleSubFormData()) && !entity.getSingleSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSingleSubFormData());
        }
        return success;
    }

    /**
     * 编辑时将获取数据格式化
     *
     * @param saasAnalysisDataDTO saasAnalysisDataDTO
     * @param result              result
     * @throws XbbException 异常
     */
    @Override
    public void formatData(SaasAnalysisDataDTO saasAnalysisDataDTO, JSONObject result) throws XbbException {
        // 格式化仓库字段
        showFormatHelp.formatLinkBusiness4Show(result, CostAdjustEnum.WAREHOUSE_ID.getAttr(), CostAdjustEnum.WAREHOUSE_ID_LINKED_TEXT.getAttr(), CostAdjustEnum.WAREHOUSE_ID.getFieldType());
    }
}
